package controller;

import entity.User;
import service.LoninService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private LoninService loninService = new LoninService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单参数
        request.setCharacterEncoding("UTF-8");
        String user = request.getParameter("user");
        String password = request.getParameter("password");

        // 登录验证
        User login = loninService.login(user, password);
        if(login == null){
            request.setAttribute("errorMsg","用户名或者密码错误，请重新登录！");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        } else{
            HttpSession session = request.getSession();
            session.setAttribute("user",login);
            request.getRequestDispatcher("index.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 注销登录信息
        HttpSession session = request.getSession();
        session.removeAttribute("user");

        // 重定向到登录页面
        response.sendRedirect("login.jsp");
    }
}
